<?php
declare (strict_types=1);

namespace app\serviceapp;

use app\model\FenggeParam;
use app\model\User;
use app\model\UserDetails;
use app\model\UserFavorite;
use app\model\UserRegister;
use app\MyException;
use app\traits\ServiceTrait;
use app\util\JwtUtil;
use app\service\AuthGroupService;
use app\model\ReportDic;
use app\util\SmsHelper;
use app\util\Tools;
use app\util\WechatHelper;
use think\facade\Cache;
use think\facade\Db;

/**
 * 用户
 * Class UserService
 * @package app\service
 */
class UserService
{

    /**
     * @param $userId
     * @return array|null|\think\Model
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getUserById($userId)
    {
        if (!$userId) throw new MyException(10002);
        $oneUser = User::where('user_id = :user_id', ['user_id' => $userId])->find();
        return $oneUser;
    }

    /**
     * 获取用户信息
     */
    public static function getUserInfo($userId)
    {
        $table_user = User::$_table;
        $table_user_detail = UserDetails::$_table;
        $oneUser = Db::name($table_user)
            ->alias('u')
            ->field("u.nick_name nickName,u.status, u.head_image headImage, u.sex, u.autograph, u.birthday, u.data_page dataPage, u.sida_num sidaNum, u.last_login_time lastLoginTime,ud.fuse,ud.tixing, ud.xijie, ud.fengge, ud.shengao, ud.tizhong,ud.nianling,ud.zhiye, ud.zhiwei, ud.aihao")
            ->join("$table_user_detail ud", "u.user_id = ud.user_id", 'left')
            ->where(['u.user_id' => $userId])->find();
        if (!$oneUser) {
            throw new MyException(10004);
        }
        $data = [];
        $data['nickName'] = $oneUser['nickName'] ?? '';
        $data['userStatus'] = $oneUser['status'] == 2 ? 1 : 0;
        $data['headImage'] = $oneUser['headImage'] ?? '';
        $data['sex'] = $oneUser['sex'] ?? 2;
        $data['autograph'] = $oneUser['autograph'] ?? '';
        $data['birthday'] = $oneUser['birthday'] ?? '';
        $data['dataPage'] = $oneUser['dataPage'] ?? 0;
        $data['sidaNum'] = $oneUser['sidaNum'] ?? 0;
        $data['lastLoginTime'] = $oneUser['lastLoginTime'] ?? '';
        $data['color'] = $oneUser['fuse'] ?? '';
        $data['bodyType'] = $oneUser['tixing'] ?? '';
        $data['detail'] = $oneUser['xijie'] ?? '';
        $data['style'] = $oneUser['fengge'] ?? '';
        $data['height'] = $oneUser['shengao'] ?? '160';
        $data['weight'] = $oneUser['tizhong'] ?? '50';
        $data['age'] = $oneUser['nianling'] ?? '26';
        $data['profession'] = $oneUser['zhiye'] ?? '';
        $data['position'] = $oneUser['zhiwei'] ?? '';
        $data['hobby'] = $oneUser['aihao'] ?? '';

        return $data;
    }

    /**
     * 修改用户信息
     * @param $data
     */
    public static function editInfo($data)
    {
        $oneUser = static::getUserById($data['userId']);
        if (empty($oneUser)) {
            throw new MyException(10004);
        }

        $data = array_filter($data);
        try {
            $oneUser->save($data);
        } catch (\Exception $e) {
            throw new MyException(10005, $e->getMessage());
        }

        return (object)[];

    }

    /**
     * 获取收藏数
     */
    public static function getFavoriteCount($userId)
    {
        $count = UserFavorite::where('user_id=:user_id', ['user_id' => $userId])->count();
        return $count;
    }

    /**
     * 登录注册
     * @param $phone
     */
    public static function loginByPhone($phone, $module = 'login')
    {
        $userRegisterTable = UserRegister::$_table;
        $findByPhone = Db::name($userRegisterTable)->where(['phone' => $phone])->find();

        if (empty($findByPhone)) {
            // 没有数据，则进行注册
            $regData['phone'] = $phone;
            $userid = UserRegisterService::registerByPhone($phone); // 注册用户
            $regData['user_id'] = $userid;
            static::register($regData); // 注册用户
        } else {
            $userid = $findByPhone['user_id'];
            static::updateUserByUserid($userid);
        }

        $genToken = [];
        $genToken['user_id'] = $userid;
        $genToken['phone'] = $phone;
        $userToken = static::genToken($genToken);

        $returnData['userId'] = $userid;
        $returnData['accessKey'] = $userToken;
        return $returnData;
    }

    /**
     * APP微信登录
     * @param $data
     * @return mixed
     */
    public static function loginByWechat($data)
    {
        $unionid = $data['unionid'];
        $nick_name = $data['nick_name'];
        $avatar = $data['avatar'];
        $sex = $data['sex'];
        $openid = $data['openid'];
        $openidType = $data['openIdType'] ?? 0;
        if (empty($unionid)) throw new MyException(12013);

        $findByPhone = UserRegister::where(['uid' => $unionid])->find();

        if (empty($findByPhone)) {
            // 没有数据，则进行注册
            $userid = UserRegisterService::registerByUnionId($unionid); // 注册用户
            $regData['user_id'] = $userid;
            $regData['nick_name'] = $nick_name;
            $regData['sex'] = $sex;
            $regData['head_image'] = $avatar;
            switch ($openidType) {
                // 0 APP 1 小程序 2 web
                case 1:
                    $regData['open_id_xcx'] = $openid;
                    break;
                case 2:
                    $regData['open_id_web'] = $openid;
                    break;
                default:
                    $regData['open_id_app'] = $openid;
            }
            static::register($regData); // 注册用户
        } else {
            $userid = $findByPhone['user_id'];
            static::updateUserByUserid($userid);
        }

        $genToken = [];
        $genToken['user_id'] = $userid;
        $genToken['phone'] = '';
        $userToken = static::genToken($genToken);

        $returnData['userId'] = $userid;
        $returnData['accessKey'] = $userToken;
        return $returnData;
    }

    /**
     * 小程序登录
     * @param $data
     * @return mixed
     */
    public static function loginByMinWechat($data)
    {
        $loginInfo = WechatHelper::getWechatLoginInfo($data['code'], $data['iv'], $data['encryptedData']); // 以code换取openid
        if (empty($loginInfo)) throw new MyException(12006);
        $loginInfo = json_decode($loginInfo, true);
        $unionId = isset($loginInfo['unionId']) ? $loginInfo['unionId'] : '';
        $openId = isset($loginInfo['openId']) ? $loginInfo['openId'] : '';

        if (empty($loginInfo)) {
            throw new MyException(12006);
        }
        if (empty($openId) || empty($unionId)) {
            throw new MyException(12013);
        }

        $data['openid'] = $openId;
        $data['unionid'] = $unionId;
        $data['openIdType'] = 1; // 0 APP 1 小程序 2 web
        return static::loginByWechat($data);
    }

    /**
     * 注册
     * @param array $data
     */
    public static function register($data)
    {
        $insert_data = [
            "user_id" => $data["user_id"], // 登录账号 手机号
            "nick_name" => $data["phone"] ?? $data['nick_name'] ?? static::getRegisterName(), // 登录账号 手机号
            "head_image" => $data['head_image'] ?? '',
            "sex" => $data['sex'] ?? 0, // 性别 0-未知 1-男 2-女
            "open_id_xcx" => $data['open_id_xcx'] ?? '',
            "open_id_web" => $data['open_id_web'] ?? '',
            'open_id_app' => $data['open_id_app'] ?? '',
            'autograph' => $data["autograph"] ?? '',
            'wx_number' => $data['wx_number'] ?? '',
            "inviter_user_id" => $data['inviter_user_id'] ?? 0,
            'create_time' => date("Y-m-d H:i:s"),
            'update_time' => date("Y-m-d H:i:s"),
            'last_login_time' => date("Y-m-d H:i:s"),
        ];
        User::insertGetId($insert_data);
    }

    /**
     * 修改
     * @param $userid
     */
    public static function updateUserByUserid($userid)
    {
        $userTable = User::$_table;
        Db::name($userTable)->where(['user_id' => $userid])->update(['last_login_time' => date('Y-m-d H:i:s')]);
    }

    /**
     * 查找
     * @param $userid
     */
    public static function getInfoById($userid)
    {
        $userTable = User::$_table;
        return Db::name($userTable)->where(['user_id' => $userid])->find();
    }

    /**
     * 自动生成昵称
     */
    public static function getRegisterName()
    {
        $prefix = '搭你';
        return $prefix . mt_rand(1, 999999) . mt_rand(1, 9);
    }

    /**
     * 生成token
     * @param $data
     * @return string
     */
    public static function genToken($data)
    {
        // 数据处理和令牌获取
        $time = time();

        // 令牌生成
        $payload['user_id'] = $data['user_id'];
        $payload['phone'] = $data['phone'];
        $payload['login_time'] = $time;
        $user_token = think_encrypt(JwtUtil::encode($payload));
        return $user_token;
    }
}
